<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    top="100px"
    :close-on-click-modal="false"
    :before-close="closeBefore"
    :append-to-body="true"
    width="960px"
    class="component-prods-select"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName') + ':'">
        <el-input
          v-model.trim="prodName"
          style="width: 180px;"
          :placeholder="$t('product.prodName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings') + ':'">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{
            $t("order.query")
          }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{
            $t("shop.resetMap")
          }}
        </div>
      </el-form-item>
    </el-form>
    <div class="prods-select-body">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        :header-cell-style="{ height: '42px', background: '#F6F7FA', color: '#666666', 'font-weight': '500' }"
        :cell-style="{ height: '64px', padding: '8px 0', color: '#000' }"
        :row-key="getRowKeys"
        style="width: 100%"
        height="420"
        @selection-change="selectChangeHandle"
      >
        <el-table-column
          v-if="isSingle"
          width="50"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div class="prods-select-radio">
              <el-radio
                v-model="singleSelectProdId"
                :label="scope.row.prodId"
                @change="getSelectProdRow(scope.row)"
              >
                &nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isSingle"
          type="selection"
          :reserve-selection="true"
          header-align="center"
          align="center"
          width="50"
        />
        <el-table-column
          align="left"
          width="550"
          :label="$t('product.prodInfo')"
        >
          <template #default="scope">
            <div class="prod-info">
              <ImgShow
                :src="scope.row.pic"
                :img-style="{ width: '48px', height: '48px' }"
              />
              <span class="prod-name">{{ scope.row.prodName }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 销售价(元) -->
        <el-table-column
          prop="price"
          :label="$t('product.sellingPrice')"
        >
          <template #default="scope">
            <span class="prod-name">{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalStocks"
          :label="$t('product.totalStocks')"
        />
      </el-table>
    </div>
    <div class="pagination-box">
      <el-pagination
        style="margin-top:15px"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>
    <template #footer>
      <span>
        <div
          class="default-btn"
          @click="cancelFn"
        >{{
          $t("crud.filter.cancelBtn")
        }}</div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="submitProds()"
        >{{
          $t("crud.filter.submitBtn")
        }}</div>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onActivated, reactive, toRefs } from 'vue'
import { ElMessageBox } from 'element-plus'

const emit = defineEmits(['refreshSelectProds', 'closeProdsSelect'])
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  // 0普通商品 1拼团 2秒杀 3积分 5活动商品
  prodType: {
    default: null,
    type: Number
  },
  dataUrl: {
    default: '/admin/search/prod/page',
    type: String
  },
  giveawayId: {
    default: 0,
    type: [String, Number]
  },
  groupActivityId: {
    default: null,
    type: [String, Number]
  },
  mustNotProdTypes: {
    default: null,
    type: String
  }
})

const Data = reactive({
  visible: false,
  dataForm: {
    product: ''
  },
  singleSelectProdId: 0,
  allData: [],
  selectProds: [],
  dataList: [],
  prodName: '',
  shopCategoryId: null,
  pageIndex: 1,
  pageSize: 10,
  totalPage: 0,
  dataListLoading: false,
  addOrUpdateVisible: false,
  dataListSelections: [],
  categoryList: [],
  selectedCategory: [],
  categoryTreeProps: {
    value: 'categoryId',
    label: 'categoryName'
  }
})

const { visible, dataForm, singleSelectProdId, dataList, prodName, pageIndex, pageSize, totalPage, dataListLoading, categoryList, selectedCategory, categoryTreeProps } = toRefs(Data)

onActivated(() => {
  getDataList()
})

const prodTableRef = ref()
onBeforeUnmount(() => {
  prodTableRef.value.clearSelection()
})

// 获取数据列表
const init = (selectProds) => {
  Data.singleSelectProdId = 0
  Data.selectProds = selectProds || []
  Data.visible = true
  Data.dataListLoading = true
  if (Data.selectProds instanceof Array) {
    Data.selectProds.forEach(row => {
      Data.dataListSelections.push(row)
    })
  } else {
    Data.dataListSelections = Data.selectProds
  }
  getDataList()
  getCategoryList()
}

const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      status: 1
    })
  }).then(({ data }) => {
    Data.categoryList = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}

const cancelFn = () => {
  Data.dataListSelections = []

  clean()
  Data.visible = false
  prodTableRef.value.clearSelection()
}

const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: Data.pageIndex,
          size: Data.pageSize,
          prodName: Data.prodName ? Data.prodName : null,
          keyword: Data.prodName ? Data.prodName : null,
          prodType: props.prodType,
          shopCategoryId: Data.shopCategoryId ? Data.shopCategoryId : null,
          status: 1,
          giveawayId: props.giveawayId ? props.giveawayId : null,
          groupActivityId: props.groupActivityId ? props.groupActivityId : null,
          isActive: 1, // 过滤掉活动商品
          mustNotProdTypes: props.mustNotProdTypes ? props.mustNotProdTypes : null
        }
      )
    )
  }).then(({ data }) => {
    Data.dataList = data.records
    Data.totalPage = data.total
    Data.dataListLoading = false
    if (Data.selectProds.length) {
      nextTick(() => {
        Data.selectProds.forEach(row => {
          const index = Data.dataList.findIndex((prodItem) => prodItem.prodId === row.prodId)
          if (index >= 0) {
            prodTableRef.value.toggleRowSelection(Data.dataList[index], true)
          }
        })
      })
    }
  })
}

// 每页数
const sizeChangeHandle = (val) => {
  Data.pageSize = val
  Data.pageIndex = 1
  getDataList()
}

// 当前页
const currentChangeHandle = (val) => {
  Data.pageIndex = val
  getDataList()
}

// 单选商品事件
const getSelectProdRow = (row) => {
  Data.dataListSelections = [row]
}

// 多选点击事件
const selectChangeHandle = (selection) => {
  Data.dataListSelections = selection
}

const getRowKeys = (row) => {
  return row.prodId
}

/**
 * 获取分类id
 */
const handleChange = (val) => {
  if (val) {
    Data.shopCategoryId = val[val.length - 1]
  } else {
    Data.shopCategoryId = null
  }
}

/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  Data.pageIndex = 1
  getDataList()
}

/**
 * 清空搜索条件
 */
const clean = () => {
  Data.prodName = ''
  Data.shopCategoryId = null
  Data.selectedCategory = idList(Data.categoryList, Data.shopCategoryId, 'categoryId', 'children').reverse()
}

// 确定事件
const submitProds = () => {
  // 商品单选情况
  if (props.isSingle) {
    Data.dataListSelections.length && emit('refreshSelectProds', Data.dataListSelections[0])
    Data.dataListSelections = []
    Data.visible = false
    // 商品多选情况
  } else {
    const prods = []
    Data.dataListSelections.forEach(item => {
      const prodIndex = prods.findIndex((prod) => prod.prodId === item.prodId)
      if (prodIndex === -1) {
        prods.push(
          {
            prodId: item.prodId,
            prodName: item.prodName,
            pic: item.pic,
            activityId: item.activityId,
            prodType: item.prodType,
            oriPrice: item.oriPrice,
            price: item.price,
            brief: item.brief,
            activityPrice: item.activityPrice
          }
        )
        // prods.push({ prodId: item.prodId, prodName: item.prodName, pic: item.pic, groupActivityId: item.groupActivityId, seckillActivityId: item.seckillActivityId })
      }
    })
    // Data.$refs.prodTable.clearSelection()
    let msgInfo = ''
    // 秒杀活动选择商品的提示
    if (props.dataUrl.includes('canSekcillProdPage')) {
      msgInfo = $t('components.seckillWhetherToContinue')
    } else if (props.dataUrl.includes('getNotGroupProdPage')) {
      // 拼团活动选择商品的提示
      msgInfo = $t('components.groupWhetherToContinue')
    }
    if (msgInfo !== '' && msgInfo !== null) {
      prodIsSeckill(prods, msgInfo)
    } else {
      emit('refreshSelectProds', prods)
      Data.dataListSelections = []
      Data.visible = false
    }
  }
}

/**
 * 查询商品是否在参与秒杀活动
 */
const prodIsSeckill = (prods, msgInfo) => {
  const prodIds = []
  for (let index = 0; index < prods.length; index++) {
    prodIds.push(prods[index].prodId)
  }
  http({
    url: http.adornUrl('/admin/discount/prodIsDiscount'),
    method: 'post',
    data: prodIds
  }).then(({ data }) => {
    const msg = data
    if (msg !== undefined && msg !== null && msg !== '') {
      ElMessageBox.confirm(msgInfo, $t('text.tips'), {
        confirmButtonText: $t('crud.filter.submitBtn'),
        cancelButtonText: $t('crud.filter.cancelBtn'),
        type: 'warning'
      }).then(() => {
        emit('refreshSelectProds', prods)
        Data.dataListSelections = []
        Data.visible = false
      })
    } else {
      emit('refreshSelectProds', prods)
      Data.dataListSelections = []
      Data.visible = false
    }
  })
}

/**
 * 关闭前操作
 */
const closeBefore = (done) => {
  Data.dataListSelections = []
  prodTableRef.value.clearSelection()
  clean()
  emit('closeProdsSelect')
  Data.visible = false
  done()
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.component-prods-select {
  :deep(.el-input.el-input--small),
  :deep(.el-cascader.el-cascader--small) {
    width: 180px;
  }
  .prods-select-body {
    height: 420px;
  }
  .prods-select-radio {
    :deep(.el-radio__label) {
      display: none;
    }
  }
  .prod-info {
    display: flex;
    align-items: center;
    .prod-name {
      flex: 1;
      margin-left: auto;
      padding: 0 30px 0 10px;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
      word-break: break-word;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 20px;
    }
  }
  :deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 6px;
    height: 439px;
    background: #F7F8FA;
    opacity: 1;
    border-radius: 4px;
  }
  // 滚动条的滑块
  :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    width: 6px;
    height: 150px;
    background: #E9ECF3;
    opacity: 1;
    border-radius: 4px;
  }

  .pagination-box{
    display: flex;
    justify-content: flex-end;
  }
}
</style>
